var AdController = angular.module('AdController', ['ngMaterial']);
AdController.config(function($mdThemingProvider) {
  $mdThemingProvider.theme('default')
    .primaryPalette('indigo')
    .accentPalette('green', {
    	'default':"500",
    	'hue-1':"300"
    });
}
);

function indexOf(key, content, target){
	for( var i = 0; i < target.length; i++ ){
		if(target[i][key] == content){
			return i;
		}
	}
	return -1;
}
AdController.controller('MainCtrl', function($scope, $http, $location, $mdDialog, $mdMedia, $mdToast){
	$scope.set_image_count = function(){
		$http.get('/accounts/imageData').success(function(data){
			$scope.total = data.total;
			$scope.assigned = data.assigned;
			$scope.remain = data.remain;
		});
	}
	$scope.get_user_list = function(){
		$http.get('/accounts/present').success(function(data){
			$scope.users = data;
		})
	}
	$scope.update = function(){
		$scope.get_user_list();
		$scope.set_image_count();
	}
	$scope.total=100;
	$scope.assigned=50;
	$scope.remain=50;
	$scope.users=[];
	$scope.update();
	$scope.showManageDialog = function(username, ev){
		var useFullScreen = ($mdMedia('sm') || $mdMedia('xs'))  && $scope.customFullscreen;
		$mdDialog.show({
		  controller: ManageController,
		  templateUrl: '/static/html/user_management.tmp.html',
		  parent: angular.element(document.body.div),
		  targetEvent: ev,
		  clickOutsideToClose:true,
		  fullscreen: useFullScreen,
		  locals: { curruser: username, userinfo: $scope.users[indexOf('username', username, $scope.users)], $http: $http, $mdToast:$mdToast }
		})
		.then(function(answer) {
		  $scope.status = 'You said the information was "' + answer + '".';
		}, function() {
		  $scope.status = 'You cancelled the dialog.';
		});
		$scope.$watch(function() {
		  return $mdMedia('xs') || $mdMedia('sm');
		}, function(wantsFullScreen) {
		  $scope.customFullscreen = (wantsFullScreen === true);
		});
		
	};
	$scope.showNewDialog = function(ev){
		var useFullScreen = ($mdMedia('sm') || $mdMedia('xs')) && $scope.customFullscreen;
		$mdDialog.show({
			controller: NewController,
			templateUrl: '/static/html/new_user.tmp.html',
			parent: angular.element(document.body.div),
			targetEvent: ev,
			clickOutsideToClose: true,
			fullscreen: useFullScreen,
			locals: {$http, $http, $mdToast:$mdToast}
		}).then(function(answer){
			$scope.update();
		}, function() {
			$scope.update();
		});
		$scope.$watch(function(){
			return $mdMedia('xs') || $mdMedia('sm');
		}, function(wantsFullScreen){
			$scope.customFullscreen = (wantsFullScreen === true);
		});
	}

	$scope.deleteUser = function(username){
		var opt = {
			url: '/accounts/removeUser',
			method: 'POST',
			data:JSON.stringify({
				username:username
			}),
			headers: { 'Content-Type': 'application/json' }
		};
		$http(opt).success(function(data){
			if( data ){
				showToast($mdToast, "User Removed Successfully");
			}else{
				showToast($mdToast, "User Removed Failed");
			}
			$scope.update();
		})
	}
	
});

function ManageController($scope, $mdDialog, $http ,curruser, userinfo ,$mdToast){
	$scope.curruser = curruser;
	$scope.assign = {
		description:"Image to be assigned",
		min:0
	}
	$scope.tagged = 0;
	$scope.remain = 0;
	$scope.total = 1;
	$scope.getUserImageCount = function(){
		var opt = {
			url: '/accounts/userimageData',
			method: 'POST',
			data:JSON.stringify({
				username:$scope.curruser
			}),
			headers: { 'Content-Type': 'application/json' },
		}
		$http(opt).success(function(data){
			$scope.tagged = data.tagged;
			$scope.remain = data.remain;
			$scope.total = data.total;
			if (data.total == 0){
				$scope.percent = 0;
			}else{
				$scope.percent = 100 * ($scope.tagged / $scope.total );	
			}
		});
	}
	$scope.update = function(){
		$scope.getUserImageCount()
	}
	$scope.update();
	$scope.hide = function() {
		$mdDialog.hide();
	};
	$scope.cancel = function() {
		$mdDialog.cancel();
	};
	$scope.answer = function(answer) {
		$mdDialog.hide(answer);
	};
	$scope.setNewPass = function(){
		if( $scope.password == $scope.copassword ){
			var opt = {
				url: '/accounts/save',
				method: 'POST',
				data:JSON.stringify({
					username:$scope.curruser,
					password:$scope.password
				}),
				headers: { 'Content-Type': 'application/json' }
			}
			$http(opt).success(function(data){
				if( data.isChanged ){
					showToast($mdToast, "Password Changed Successfully");
				}else{
					showToast($mdToast, "Password Changed Failed");
				}
			});
		}else{
			showToast($mdToast, "Password not Match");
		}
	}
	$scope.assign = function(){
		//var numberReg = new RegExp("^\+?[1-9][0-9]*$");
		if(userinfo.isAdministrator){
			showToast($mdToast, "Can not assign Image to Administrator");
		}
		if( true ){
			if( !userinfo.isReviewer && !userinfo.isAdministrator ){
				var opt={
					url: '/accounts/assignImages',
					method: 'POST',
					data: {
						username:$scope.curruser,
						imageCount: $scope.assign_num
					},
					headers:{ 'Content-Type': 'application/json'}
				}
				console.log(opt);
				$http(opt).success(function(data){
					console.log(data);
					if(data.isSuccessful){
						showToast($mdToast, "Image Assigned Successfully");
						$scope.update();
					}else{
						showToast($mdToast, data.errorMessage);
					}
				});
			}else if ( user.isReviewer ){
				var opt={
					url: '/accounts/assignReviewerImages',
					method: 'POST',
					data: JSON.stringify({
						username:$scope.curruser,
						imageCount: $scope.assign_num
					}),
					headers:{ 'Content-Type': 'application/json'}
				}
				$http(opt).success(function(data){
					console.log(data);
					if(data.isSuccessful){
						showToast($mdToast, "Image Assigned Successfully");
						$scope.update();
					}else{
						showToast($mdToast, data.errorMessage);
					}
				});
			}else{
				showToast($mdToast, "Can not assign images to Administrator");
			}
		}else{
			console.log("hello")
			showToast($mdToast, "Please input a valid number");
		}
	}
	$scope.withdraw = function(){
		var opt={
			url: '/accounts/withdraw',
			method: 'POST',
			data:JSON.stringify({
				username:$scope.curruser,
				count: $scope.withdraw_num
			}),
			headers:{ 'Content-Type': 'application/json'}
		}
		console.log(opt);
		$http(opt).success(function(data){
			console.log(data);
			if(data.isSuccessful){
				showToast($mdToast, "Image Withdraw Successfully");
				$scope.update();
			}else{
				showToast($mdToast, "Image Withdraw Failed");
			}
		});
	}
}

function NewController($scope, $mdDialog, $http, $mdToast){
	$scope.hide = function() {
		$mdDialog.hide();
	};
	$scope.cancel = function() {
		$mdDialog.cancel();
	};
	$scope.create_user = function(){
		var username = $scope.new_username,
			password = $scope.newpassword,
			copassword = $scope.newcopassword,
			isReviewer = $scope.newisReviewer || false;
		if( username.length > 0 && password == copassword && password.length > 0){
			var opt = {
				url:'/accounts/addUser',
				method:'POST',
				data:{username:username, password:password, isReviewer:isReviewer},
				headers: {'Content-Type':'application/json'}
			}
			console.log(opt);
			$http(opt).success(function(data){
				if(data.isAccountValid){
					showToast($mdToast, "User Created Successfully");
					$mdDialog.hide();
				}else{
					showToast($mdToast, "User can not be Created");
				}
			})
		}
	}
}

var last = {
    bottom: false,
    top: true,
    left: false,
    right: true
};

var toastPosition = angular.extend({},last);

function sanitizePosition() {
	var current = toastPosition;
	if ( current.bottom && last.top ) current.top = false;
	if ( current.top && last.bottom ) current.bottom = false;
	if ( current.right && last.left ) current.left = false;
	if ( current.left && last.right ) current.right = false;
	last = angular.extend({},current);
}

var getToastPosition = function() {
    sanitizePosition();
    return Object.keys(toastPosition)
      .filter(function(pos) { return toastPosition[pos]; })
      .join(' ');
};

function showToast($mdToast, msg){
	var pinTo = getToastPosition();
    var toast = $mdToast.simple()
      .textContent(msg)
      .highlightAction(true)
      .position(pinTo);
    $mdToast.show(toast).then(function(response) {
      if ( response == 'ok' ) {
      }
    });
}
